<template>
  <div class="reset-wrapper">
    <header>
      <i class="fa fa-angle-left" @click="back"></i>
      <h1>{{ isUserLogin ? '重置用户信息' : '重置商家信息' }}</h1>
    </header>

    <form @submit.prevent="submitForm" class="form-box">
      <div v-if="isUserLogin">
        <div class="form-group">
          <label for="userId">用户ID:</label>
          <input type="text" id="userId" v-model="user.userId" required readonly>
        </div>
        <div class="form-group">
          <label for="password">新密码:</label>
          <input type="password" id="password" v-model="user.password" required>
        </div>
        <div class="form-group">
          <label for="userName">用户名:</label>
          <input type="text" id="userName" v-model="user.userName" required>
        </div>
        <div class="form-group">
          <label for="userSex">性别:</label>
          <select id="userSex" v-model="user.userSex" required>
            <option value="1">男</option>
            <option value="0">女</option>
          </select>
        </div>
        <div class="form-group">
          <label for="userImg">用户图片:</label>
          <div>
            <input type="text" id="userImg" v-model="user.userImg" required readonly>
            <button type="button" @click="triggerFileInput('user')">选择图片</button>
            <input type="file" ref="userFileInput" @change="handleFileChange('user')" style="display: none;">
            <img v-if="user.userImg" :src="user.userImg" alt="用户图片" style="max-width: 100px; max-height: 100px; margin-top: 10px;">
          </div>
        </div>
      </div>
      <div v-if="!isUserLogin">
        <div class="form-group">
          <label for="businessId">商家ID:</label>
          <input type="text" id="businessId" v-model="business.businessId" required readonly>
        </div>
        <div class="form-group">
          <label for="password">新密码:</label>
          <input type="password" id="bpassword" v-model="business.password" required>
        </div>
        <div class="form-group">
          <label for="businessName">商家名:</label>
          <input type="text" id="businessName" v-model="business.businessName" required>
        </div>
        <div class="form-group">
          <label for="businessAddress">商家地址:</label>
          <input type="text" id="businessAddress" v-model="business.businessAddress" required>
        </div>
        <div class="form-group">
          <label for="businessExplain">商家简介:</label>
          <input type="text" id="businessExplain" v-model="business.businessExplain" required>
        </div>
        <div class="form-group">
          <label for="starPrice">商家starPrice:</label>
          <input type="number" id="starPrice" v-model="business.starPrice" step="0.01" required>
        </div>
        <div class="form-group">
          <label for="deliveryPrice">商家deliveryPrice:</label>
          <input type="number" id="deliveryPrice" v-model="business.deliveryPrice" step="0.01" required>
        </div>
        <div class="form-group">
          <label for="businessImg">商家图片:</label>
          <div>
            <input type="text" id="businessImg" v-model="business.businessImg" required readonly>
            <button type="button" @click="triggerFileInput('business')">选择图片</button>
            <input type="file" ref="businessFileInput" @change="handleFileChange('business')" style="display: none;">
            <img v-if="business.businessImg" :src="business.businessImg" alt="商家图片" style="max-width: 100px; max-height: 100px; margin-top: 10px;">
          </div>
        </div>
      </div>
      <div class="button-reset">
        <button @click="submitForm">{{ isUserLogin ? '更新用户信息' : '更新商家信息' }}</button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'Reset',
  data() {
    return {
      isUserLogin: true, // 根据登录类型设置
      user: {
        userId: '',
        password: '',
        userName: '',
        userSex: null,
        userImg: '', // 用户图片的 Base64 格式
        delTag: 1
      },
      business: {
        businessId: '',
        password: '',
        businessName: '',
        businessAddress: '',
        businessExplain: '',
        starPrice: 0.0,
        deliveryPrice: 0.0,
        businessImg: '' // 商家图片的 Base64 格式
      }
    };
  },
  created() {
    // 从 sessionStorage 中获取用户或商家信息
    this.user = this.$getSessionStorage('user') || {
      userId: '',
      password: '',
      userName: '',
      userSex: null,
      userImg: '',
      delTag: 1
    };
    this.business = this.$getSessionStorage('business') || {
      businessId: '',
      password: '',
      businessName: '',
      businessAddress: '',
      businessExplain: '',
      starPrice: 0.0,
      deliveryPrice: 0.0,
      businessImg: ''
    };
    // 判断当前登录类型
    this.isUserLogin = sessionStorage.getItem('business') === null;
    // 根据登录类型加载对应的信息
    if (this.isUserLogin) {
      this.loadUser();
    } else {
      this.loadBusiness();
    }
  },
  methods: {
    back() {
      // 返回上一页
      this.$router.push('/my');
    },
    loadUser() {
      // 加载用户信息
      let userurl = `/UserController/getById/${this.user.userId}`;
      this.$axios.get(userurl).then(response => {
        this.user = response.data.result;
      }).catch(error => {
        console.error('加载用户错误:', error);
      });
    },
    loadBusiness() {
      // 加载商家信息
      let businessurl = `/BusinessAdminController/getBusinessById/${this.business.businessId}`;
      this.$axios.get(businessurl).then(response => {
        this.business = response.data.result;
      }).catch(error => {
        console.error('加载商家错误:', error);
        alert('加载商家信息失败');
      });
    },
    submitForm() {
      // 提交表单
            let formData = new FormData();
            if (this.isUserLogin) {
              // 提交用户信息更新的逻辑
              formData.append('userId', this.user.userId);
              formData.append('password', this.user.password);
              formData.append('userName', this.user.userName);
              formData.append('userSex', this.user.userSex);
              formData.append('userImg', this.user.userImg);
              formData.append('delTag', this.user.delTag);
              let updateurl = `/UserController/updateUser`;
              this.$axios.post(updateurl, formData, {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }).then(response => {
          if (response.data.result > 0) {
            alert('用户信息更新成功');
            this.$setSessionStorage('user', this.user);
            this.back();
          } else {
            alert('更新用户失败');
          }
        }).catch(error => {
          console.error('更新用户错误:', error);
          alert('更新用户时发生错误');
        });
      } else {
        // 提交商家信息更新的逻辑
                formData.append('businessId', this.business.businessId);
                formData.append('password', this.business.password);
                formData.append('businessName', this.business.businessName);
                formData.append('businessAddress', this.business.businessAddress);
                formData.append('businessExplain', this.business.businessExplain);
                formData.append('starPrice', this.business.starPrice);
                formData.append('deliveryPrice', this.business.deliveryPrice);
                formData.append('businessImg', this.business.businessImg);
                let updateurl = `/BusinessAdminController/updateBusiness`;
                this.$axios.post(updateurl, formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                }).then(response => {
          if (response.data.result > 0) {
            alert('商家信息更新成功');
            this.$setSessionStorage('business', this.business);
            this.back();
          } else {
            alert('更新商家失败');
          }
        }).catch(error => {
          console.error('更新商家错误:', error);
          alert('更新商家时发生错误');
        });
      }
    },
    triggerFileInput(type) {
      // 触发文件选择
      if (type === 'user') {
        this.$refs.userFileInput.click();
      } else if (type === 'business') {
        this.$refs.businessFileInput.click();
      }
    },
    handleFileChange(type) {
      // 处理文件选择
      const fileInput = type === 'user' ? this.$refs.userFileInput : this.$refs.businessFileInput;
      const file = fileInput.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          if (type === 'user') {
            this.user.userImg = e.target.result;
          } else if (type === 'business') {
            this.business.businessImg = e.target.result;
          }
        };
        reader.readAsDataURL(file);
      }
    }
  }
};
</script>

<style scoped>
.reset-wrapper {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  background-color: #f8f8f8;
  border-bottom: 1px solid #ddd;
}

header i {
  font-size: 24px;
  cursor: pointer;
}

.form-box {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 5px;
  margin-top: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.button-reset {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-reset button {
  padding: 10px 20px;
  background-color: #e74c3c;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.button-reset button:hover {
  background-color: #c0392b;
}
</style>